//
//  KLMHomeMemberDetailController.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/17.
//

import UIKit

class KLMHomeMemberDetailController: KLMBaseHomeTableController {

    var myRoleType: HomeMemberRoleType = .user
    var currentUser: KLMHomeUser
    var lookUser: KLMHomeUser
    let homeId: Int
    private var popView: YBPopupMenu?
    private var lastSelectIndex: IndexPath?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        homeItems = KLMHomeItem.homeMemberDetailItems(currentUser: currentUser, lookUser: lookUser)
    }
    init(homeId: Int, currentUser: KLMHomeUser, lookUser: KLMHomeUser) {
        self.homeId = homeId
        self.currentUser = currentUser
        self.lookUser = lookUser
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func tableViewDidSelect(item: KLMHomeItem, at: IndexPath, on: UITableView) {
        super.tableViewDidSelect(item: item, at: at, on: on)
        if item.actionType == .rename {
            if !item.showArrow { return }
            /// 修改名字
            let vc = KLMBaseModalController(type: .rename, operTitle: "重命名", textFieldTip: item.rightTitle, confirmBlock:  { [weak self] text, type in
                guard let self = self else { return }
                if type == .rename {
                    self.updateName(newName: text!) {
                        var newItem = item
                        newItem.rightTitle = text
                        self.homeItems[at.section][at.row] = newItem
                        on.reloadRows(at: [at], with: .fade)
                    }
                }
            })
            modalVc(vc: vc)
        } else if item.actionType == .updateRoleType {
            if !item.showArrow { return }
            ///  修改权限
            showSelectRoleList(on.cellForRow(at: at)!)

        } else if item.actionType == .deleteMember || item.actionType == .cancelInvite {
            ///  移除成员、撤销邀请
            deleteMember()

        } else if item.actionType == .reInvite {
            ///  重新邀请
            reinvite()
        }
    }
    
    /// 更新成员昵称
    func updateName(newName: String, success: @escaping () -> ()) {
        SVProgressHUD.show()
        KLMRequest.updateHomeUserInfo(meshId: homeId, userId: lookUser.userId, homeNickname: newName) { response in
            SVProgressHUD.dismiss()
            NotificationCenter.post(.homeMemberChanged)
            success()
        } failure: { error in
            SVProgressHUD.dismiss()
            KLMHttpShowError(error)
        }
    }
    /// 移除成员 / 撤销邀请
    func deleteMember() {
        SVProgressHUD.show()
        KLMRequest.deleteUser(meshId: homeId, userId: lookUser.userId) { response in
            SVProgressHUD.dismiss()
            self.navigationController?.popViewController(animated: true)
            NotificationCenter.post(.homeMemberChanged)
            
        } failure: { error in
            SVProgressHUD.dismiss()
            KLMHttpShowError(error)
        }
    }
    /// 重新邀请
    func reinvite() {
        KLMRequest.getSingleCode(meshId: homeId, username: "待加入", nickName: "新成员") { response in
            if let code = response as? String {
                /// 添加成员
                let text = code
                self.presentSystemShare(
                    activityItems: [text],
                    excludedActivityTypes: [.saveToCameraRoll, .airDrop]
                ) { completed, activityType in
                    if completed {
                        print("分享成功，类型：\(activityType?.rawValue ?? "未知")")
                        self.navigationController?.popViewController(animated: true)
                        NotificationCenter.post(.homeMemberChanged)
                    }
                }
            }
        } failure: { error in
            KLMHttpShowError(error)
        }
    }
    
    func promoteRoleType(roleId: Int, success: @escaping () -> ()) {
        SVProgressHUD.show()
        // 0降级为成员 1提升为管理员
        KLMRequest.promoteDemoteUser(meshId: homeId, userId: lookUser.userId, promote: roleId) { response in
            
            SVProgressHUD.dismiss()
            success()
            
            self.homeItems[1][1].rightTitle = self.lookUser.roleType == HomeMemberRoleType.user.rawValue ? "管理员" : "普通用户"
            self.tableView.reloadRows(at: [IndexPath(row: 1, section: 1)], with: .fade)
            
            
            NotificationCenter.post(.homeMemberChanged)
        } failure: { error in
            SVProgressHUD.dismiss()
        }
    }
    
    func showSelectRoleList(_ cell: UITableViewCell) {
        
        let config = PopupAppearance(
            cellHeight: 63,
            maxTableViewHeight: 456,
            animationType: .slideFromBottom
        )

        let popup = PopupTableView(
            position: .explicit(
                frame: CGRect(x: 0, y: KLMScreenH - 456, width: KLMScreenW, height: 456),
                direction: .up
            ),
            appearance: config
        )
        popup.backgroundColor = .white
        popup.tableView.separatorStyle = .none
        
        var roleItems = [
            PopupItem(title: "普通用户", subtitle: "使用设备丨使用功能", rightNormalIcon: "Role_no_select", rightSelectedIcon: "Role_select", selected: lookUser.roleType == HomeMemberRoleType.user.rawValue)
        ]
        if currentUser.userRoleType == .Owner {
            roleItems.insert(PopupItem(title: "管理员",subtitle: "管理设备和房间丨管理智能丨管理成员", rightNormalIcon: "Role_no_select", rightSelectedIcon: "Role_select", selected: lookUser.roleType == HomeMemberRoleType.Owner.rawValue), at: 0)
        }
        popup.updateItems(roleItems)
        popup.delegate = self
        
        popup.show()
    }
}

extension KLMHomeMemberDetailController: PopupTableViewDelegate {
    func headerHeight(for popupTableView: PopupTableView) -> CGFloat {
        48
    }
    func headerView(for popupTableView: PopupTableView) -> UIView? {
        let label = UILabel()
        label.configStyle(with: "角色设定", font: UIFont(safeName: "PingFangSC-Medium", size: 14), titleColor: rgba(141, 141, 141, 1))
        label.textAlignment = .center
        return label
    }
    
    func popupTableView(_ popupTableView: PopupTableView, didSelectRowAt indexPath: IndexPath) {
        popupTableView.delegate?.popupTableView(popupTableView, didTapRightButtonAt: indexPath)
    }
    
    func popupTableViewDidDismiss(_ popupTableView: PopupTableView) {
        
    }
    
    func popupTableView(_ popupTableView: PopupTableView, didTapRightButtonAt indexPath: IndexPath) {
        
        let item = popupTableView.items[indexPath.row]
        if !item.selected {
            // 0降级为成员 1提升为管理员
            promoteRoleType(roleId: (lookUser.roleType == HomeMemberRoleType.user.rawValue ? 1 : 0)) {
                
                for (index, _) in popupTableView.items.enumerated() {
                    if index == indexPath.row {
                        popupTableView.items[index].selected = true
                    } else {
                        popupTableView.items[index].selected = false
                    }
                }
                popupTableView.tableView.reloadSections(IndexSet(integer: indexPath.section), with: .fade)
            }
            popupTableView.dismiss()
        }
    }
}
